package com.linfeng.api.intercepter;

import com.auth0.jwt.interfaces.Claim;
import com.linfeng.api.annotation.AdminCheck;
import com.linfeng.api.redis.util.RedisUtils;
import com.linfeng.api.util.jwt.JwtToken;
import com.linfeng.api.util.thread.LocalUser;
import com.linfeng.common.constant.RedisKeyConstant;
import com.linfeng.common.exception.UnAuthenticatedException;
import com.linfeng.common.response.ApiCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;

/**
 * @author linfeng
 * @date 2021/1/20 20:30
 */
public class AdminAuthCheck extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Optional<AdminCheck> adminCheck = this.getAuthCheck(handler);
        if (!adminCheck.isPresent()) {
            return true;
        }

        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(bearerToken)) {
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        if(!bearerToken.startsWith("Bearer")){
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        String[] tokens = bearerToken.split(" ");
        if (!(tokens.length == 2)) {
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        String token = tokens[1];
        boolean key = redisUtils.hasKey(RedisKeyConstant.TOKEN + token);
        if(!key){
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        Map<String, Claim> map = optionalMap
                .orElseThrow(() -> new UnAuthenticatedException(ApiCode.UNAUTHORIZED));

        boolean valid = this.hasPermission(adminCheck.get(), map);
        return valid;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    private Optional<AdminCheck> getAuthCheck(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AdminCheck authCheck = handlerMethod.getMethod().getAnnotation(AdminCheck.class);
            if (authCheck == null) {
                return Optional.empty();
            }
            return Optional.of(authCheck);
        }
        return Optional.empty();
    }

    private boolean hasPermission(AdminCheck authCheck, Map<String, Claim> map) {
        Integer level = authCheck.value();
        Integer scope = map.get("scope").asInt();
        if (level > scope) {
            throw new UnAuthenticatedException(ApiCode.NOT_PERMISSION);
        }
        return true;
    }

}
